package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.RuntimeServiceImpl;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private BpmnInfoServiceImpl bpmnInfoService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeServiceImpl runtimeService;
    @Autowired
    private ServiceItemServiceImpl serviceItemService;
    @Autowired
    private TaskService taskService;

    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        TablePageInfo<CarPackageAudit> packageAuditTablePageInfo = new TablePageInfo<>(carPackageAuditMapper.selectForList(qo));
        List<CarPackageAudit> rows = packageAuditTablePageInfo.getRows();
        return packageAuditTablePageInfo ;
    }

    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long id : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public void updateInstanceId(CarPackageAudit audit) {
        carPackageAuditMapper.updateInstanceId(audit);
    }

    @Override
    public InputStream getProcessImageByAuditId(Long id) {
        // 根据id查询审核对象,判断审核对象的状态
        CarPackageAudit audit = this.get(id);
        String instanceId = audit.getInstanceId();
        List<String> highLightedActivities = null;
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            // 获取运行的任务
            highLightedActivities = runtimeService.getActiveActivityIds(instanceId);  // 根据流程实例ID获取
        } else {
            // 审核通过,审核拒绝 不需要高亮
            highLightedActivities = new ArrayList<>();
        }
        // 根据bpmnInfoService查询bpmnInfo对象,对象中存储流程定义ID
        BpmnInfo bpmnInfo = bpmnInfoService.get(audit.getBpmnInfoId());
        BpmnModel model = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        return generator.generateDiagram(model,highLightedActivities, Collections.EMPTY_LIST,"楷体","楷体","楷体");
    }

    @Override
    public void cancelApply(Long id) {
        CarPackageAudit carPackageAudit = this.get(id);
        carPackageAuditMapper.changeAuditStatus(id,CarPackageAudit.STATUS_CANCEL);
        serviceItemService.changeAuditStatus(carPackageAudit.getServiceItemId(),
                ServiceItem.AUDITSTATUS_INIT);
        runtimeService.deleteProcessInstance(carPackageAudit.getInstanceId(),"撤销审核");
    }

    @Override
    @Transactional
    public void audit(Long id, Integer auditStatus, String info) {
        // 判断状态
        CarPackageAudit carPackageAudit = this.get(id);
        if (carPackageAudit == null || !CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            throw new BusinessException("只有处于审核状态的记录才可以进行审核操作");
        }
        String userName = ShiroUtils.getUser().getUserName();
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            info = userName + "[同意],批注意见:" + info;
        }else{
            info = userName + "[拒绝],批注意见:" + info;
        }
        carPackageAudit.setInfo(carPackageAudit.getInfo() + "<br>" + info);
        Task currentTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
        taskService.setVariable(currentTask.getId(),"auditStatus",auditStatus);
        taskService.addComment(currentTask.getId(),carPackageAudit.getInstanceId(),info);
        taskService.complete(currentTask.getId());
        // 获取下一个节点
        Task nextTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            if (nextTask != null) {
                // 财务审核(当前流程图)
                carPackageAudit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
                carPackageAudit.setAuditTime(new Date());
            } else {
                // 审核通过
                serviceItemService.changeAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
                carPackageAudit.setStatus(CarPackageAudit.STATUS_PASS);
            }
        } else {
            // 审核拒绝
            serviceItemService.changeAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_INIT);
            carPackageAudit.setStatus(CarPackageAudit.STATUS_REJECT);
        }
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }
}